class TabComponent {
    constructor(container, options = {}) {
        this.container = container;
        this.tabs = options.tabs || [];
        this.activeIndex = options.activeIndex || 0;
        this.onTabChange = options.onTabChange || (() => {});
        
        this.init();
    }
    
    init() {
        this.render();
        this.bindEvents();
        this.setActiveTab(this.activeIndex);
    }
    
    render() {
        const tabsHTML = this.tabs.map((tab, index) => `
            <div class="tab-item" data-index="${index}">
                <span class="tab-text">${tab.text}</span>
            </div>
        `).join('');
        
        this.container.innerHTML = `
            <div class="tab-wrapper">
                <div class="tab-container">
                    ${tabsHTML}
                </div>
            </div>
        `;
        
        this.tabItems = this.container.querySelectorAll('.tab-item');
        this.tabContainer = this.container.querySelector('.tab-container');
    }
    
    bindEvents() {
        this.tabItems.forEach((tab, index) => {
            tab.addEventListener('click', () => {
                this.setActiveTab(index);
            });
        });
        
        // 添加触摸滑动支持
        let startX = 0;
        let scrollLeft = 0;
        
        this.tabContainer.addEventListener('touchstart', (e) => {
            startX = e.touches[0].pageX - this.tabContainer.offsetLeft;
            scrollLeft = this.tabContainer.scrollLeft;
        });
        
        this.tabContainer.addEventListener('touchmove', (e) => {
            e.preventDefault();
            const x = e.touches[0].pageX - this.tabContainer.offsetLeft;
            const walk = (x - startX) * 2;
            this.tabContainer.scrollLeft = scrollLeft - walk;
        });
    }
    
    setActiveTab(index) {
        // 移除之前的激活状态
        if (this.tabItems[this.activeIndex]) {
            this.tabItems[this.activeIndex].classList.remove('active');
        }
        
        // 设置新的激活状态
        this.activeIndex = index;
        if (this.tabItems[index]) {
            this.tabItems[index].classList.add('active');
        }
        
        // 滚动到激活的tab
        this.scrollToActiveTab();
        
        // 触发回调
        this.onTabChange(index, this.tabs[index]);
    }
    
    scrollToActiveTab() {
        const activeTab = this.tabItems[this.activeIndex];
        const containerRect = this.tabContainer.getBoundingClientRect();
        const tabRect = activeTab.getBoundingClientRect();
        
        const scrollLeft = tabRect.left - containerRect.left + this.tabContainer.scrollLeft - 
                          (containerRect.width - tabRect.width) / 2;
        
        this.tabContainer.scrollTo({
            left: scrollLeft,
            behavior: 'smooth'
        });
    }
}